<?php
switch ($_SERVER["REQUEST_METHOD"]){
    case "GET":
        get();
        break;
    case "POST":
        post();
        break;
}
function get(){
    echo <<<EOF
<!DOCTYPE html>
<html>
    <head>
        <title>藏头诗查询页面</title>    
        <style>
            i.hide{
                color:#00000000;
            }        
        </style>
    </head>
    <body>
        <h1>查询藏头诗</h1>
        <form action="#" method="post">
            <label for="keyword">关键词：</label>
            <input type="text" name="keyword" id="keyword" required><br>
            <input type="hidden" name="type" value="text">
            <input type="hidden" name="html" value="true">
            <input type="submit">
        </form>
        <p>
            API查询参数：<br>
            <code>keyword</code>：藏头诗关键词
        </p>
    </body>
</html>
EOF;
}
function post(){
    $fn = "../ciku.json";
    $a = file_get_contents($fn);
    $a = empty($a)?[]:json_decode($a,true);
    $keyword=$_POST["keyword"];
    $type=$_POST["type"]??"json";
    $html=$_POST["html"]??"false";
    $list=[];
    for ($i=0;$i<count($a);$i++){
        if ($a[$i][0]==$keyword){
            $list[]=$a[$i][1];
        }
    }
    if (count($list)==0){
        if ($type=="json"){
            die(json_encode(["status"=>false,"msg"=>"关键词不存在"]));
        }elseif ($type=="text"){
            die("该关键词不存在");
        }else{
            die("type参数不正确");
        }
    }else{
        if ($type=="json"){
            die(json_encode(["status"=>true,"data"=>$list]));
        }elseif ($type=="text"){
            $result="";
            for ($i=0;$i<count($list);$i++){
                $result.=$list[$i]."\n\n";
                if ($html=="true"){
                    $result=str_replace("\n","<br>",$result);
                }
            }
            die($result);
        }else{
            die("type参数不正确");

        }
    }
}